<?php
require_once(dirname(__FILE__) . '/inc/config.inc.php');
IsModelPriv('goodsorder');
require_once "function.php";

/*
进度：
0 已经撤单
1 报修成功
2 客服已经联系
3 系统已经派单
4 工程师接单
5 维修完成
6 已经评价
*/
$op_uid = $_SESSION['uid'];

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>发布任务</title>
    <link href="templates/style/admin.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="templates/js/jquery.min.js"></script>
    <script type="text/javascript" src="layer/layer.js"></script>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="ui/css/bootstrap.min.css">
    <link rel="stylesheet" href="ui/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="templates/js/zoomify.min.css">
    <script language="javascript" type="text/javascript" src="DatePicker/WdatePicker.js"></script>


</head>

<body style="width:890px;">
<h1 class="tit">发布任务</h1>
<div class="order_top">
    <div class="order_top1">发布人：<?php echo GetAuthor(); ?></div>
    <div class="order_top1 t_fr">创建日期：<?php echo date("Y年m月d日", time()); ?></div>
</div>
<form name="form" id="form" method="post" action="">
    <table width="200" border="1" class="table table-bordered">
        <tr>
            <td width="100" height="50">客户：<span class="maroon">*</span></td>
            <td colspan="2">

                <input type="text" id="txt_crm" class="form-control w300" list="ide" onchange="inputSelect()"/>
                <datalist id="ide" onclick="he(this.value)">
                    <?php
                    $dosql->Execute("SELECT * FROM `#@__crm` WHERE  `checkinfo`='true'   order by id asc", 10);
                    while ($row = $dosql->GetArray(10)) {
                        echo '<option value="' . $row['school'] . '--' . $row['truename'] . '"  data-value="' . $row['school'] . '--' . $row['truename'] . '"  data-id="' . $row['id'] . '" ></option>';

                    }

                    ?>
                </datalist>
                <input type="hidden" name="crmid" id="crmid" value=""/>
            </td>
            <td>
                如果没有，请先点击 增加客户 。 <a href="crm_add.php" class=" btn btn-success">增加客户</a>
            </td>
        </tr>
        <tr>
            <td>服务类型：<span class="maroon">*</span></td>
            <td>

                <select class="form-control w300" name="apply_type" id="apply_type">
                    <option value="0">请选择</option>
                    <?php
                    $dosql->Execute("SELECT * FROM `#@__tasktype` WHERE `checkinfo`='1' and is_delete=0 order by orderid ASC", 10);
                    while ($row = $dosql->GetArray(10)) {
                        echo '<option value="' . $row['id'] . '" >' . $row['classname'] . '</option>';

                    }

                    ?>
                </select>

            </td>
            <td>设备类型：<span class="maroon">*</span></td>
            <td>
                <select class="form-control w300" name="apply_device" id="apply_device">
                    <?php
                    $dosql->Execute("SELECT * FROM `#@__cascadedata` WHERE `datagroup`='device' order by orderid ASC", 10);
                    while ($row = $dosql->GetArray(10)) {
                        echo '<option value="' . $row['datavalue'] . '" >' . $row['dataname'] . '</option>';

                    }

                    ?>
                </select>
            </td>
        </tr>
        <tr>
            <td width="100" height="50">任务类型：<span class="maroon">*</span></td>
            <td colspan="3">
                <div style="width: 400px; float: left;">
                    <select class="form-control w400" name="repairid" id="repairid">
                        <option value="-1">所有</option>
                        <?php
                        $dosql->Execute("SELECT * FROM `#@__cascadedata` WHERE `datagroup`='renwu' order by orderid ASC", 10);
                        while ($row = $dosql->GetArray(10)) {
                            echo '<option data-fee="' . $row['fee'] . '" value="' . $row['datavalue'] . '" >' . $row['dataname'] . '</option>';

                        }

                        ?>
                    </select>
                </div>
                <div style="float: left"><span
                            style="height: 30px; line-height: 30px; float: left; margin-left: 18px; color: red;">数量：</span><input
                            class="form-control" style="width: 50px;" name="num" id="num" value="1" onblur="jisuan()"/>
                </div>
                <div style="float: left"><span
                            style="height: 30px; line-height: 30px; float: left; margin-left: 18px; color: red;">奖励：</span><input
                            class="form-control" style="width: 90px;" name="fee" id="fee" value="" readonly
                            unselectable="on"/></div>
            </td>
        </tr>

        <tr>
            <td>开始时间：<span class="maroon">*</span></td>
            <td><input class="Wdate" name="beginTime" id="beginTime" type="text"
                       onClick="WdatePicker({el:this,dateFmt:'yyyy-MM-dd HH:mm:ss'})"
                       value="<?php echo date("Y-m-d H:i:s", time()) ?>"></td>
            <td>
                结束时间：<span class="maroon">*</span></td>
            <td><input class="Wdate" type="text" name="endTime" id="endTime"
                       onClick="WdatePicker({el:this,dateFmt:'yyyy-MM-dd HH:mm:ss'})"
                       value="<?php echo date("Y-m-d H:i:s", time() + 14400) ?>"></td>
        </tr>

        <tr>
            <td width="100">工程师：<span class="maroon">*</span></td>
            <td colspan="3">
                <div class="" style="margin-left:10px;margin-bottom: 20px;">抢单
                    <input name="qiang" type="radio" value="q" checked/>
                    &nbsp; 派单
                    <input name="qiang" type="radio"
                           value="p"/>

                </div>
                <div id="gongchengshi" class="alert alert-success" role="alert" style="display: none;">
                    公司本部：<br/>
                    <?php
                    $dosql->Execute("SELECT * FROM  `#@__user`    WHERE level='3'   ORDER BY id asc");
                    while ($row3 = $dosql->GetArray()) {
                        echo '<label class="checkbox-inline"><input  type="checkbox" name="manageid" id="inlineCheckbox1" value="' . $row3['id'] . '" >' . $row3['school'] . '-' . $row3['truename'] . '</label>';
                    }
                    ?>
                </div>

                <div id="gongchengshi2" class="alert alert-danger" role="alert" style="display: none;">
                    授权服务站：<br/>
                    <?php
                    $dosql->Execute("SELECT * FROM  `#@__user`    WHERE level='5'   ORDER BY id asc");
                    while ($row3 = $dosql->GetArray()) {
                        echo '<label class="checkbox-inline"><input  type="checkbox" name="manageid" id="inlineCheckbox1" value="' . $row3['id'] . '" >' . $row3['school'] . '-' . $row3['truename'] . '</label>';
                    }
                    ?>
                </div>

                <input type="hidden" name="manageids" id="manageids" value=""/>
            </td>
        </tr>
        <tr>
            <td>任务详情：<span class="maroon">*</span></td>
            <td colspan="3"><textarea name="content" id="content" class="form-control w500"></textarea></td>
        </tr>

    </table>
    <input type="hidden" name="action" id="action" value="add"/>
    <input type="hidden" name="poster" id="poster" value="<?php echo GetAuthor(); ?>"/>
    <button type="button" class="btn btn-danger" onclick="cfm_order()">立即派单</button>
</form>

<script>
    //下拉选择 项目
    $("#repairid").change(function () {
        var ss = $(this).children('option:selected').get(0).dataset.fee; //任务的费用
        var num = $("#num").val();
        var fee = ss * num;
        $("#fee").val(fee);
    });

    //重新计算 费用
    function jisuan() {
        var ss = $("#repairid").children('option:selected').get(0).dataset.fee; //任务的费用
        var num = $("#num").val();
        var fee = ss * num;
        $("#fee").val(fee);
    }


    $(':radio[name="qiang"]').click(function (e) {
        var value = $(this).val();  //获取选中的radio的值
        console.log(value);
        if (value == 'p') {
            $("#gongchengshi").show();
            $("#gongchengshi2").show();
        }
        if (value == 'q') {
            $("#gongchengshi").hide();
            $("#gongchengshi2").hide();
        }
    })


    //提交表单

    function inputSelect() {
        var input_select = $("#txt_crm").val();
        var option_length = $("option").length;
        var option_id = '';
        for (var i = 0; i < option_length; i++) {
            var option_value = $("option").eq(i).attr('data-value');
            if (input_select == option_value) {
                option_id = $("option").eq(i).attr('data-id');
                break;
            }
        }
        $("#crmid").val(option_id);
    };


    function cfm_order() {
        if ($("#crmid").val() == "") {
            layer.msg('请选择客户信息');
            $("#crmid").focus();
            return false;
        }

        if ($("#repairid").val() == "-1") {
            layer.msg('请选择任务类型');
            $("#repairid").focus();
            return false;
        }


        if ($("#content").val() == "") {
            layer.msg('请输入任务信息');
            $("#content").focus();
            return false;
        }

        var beginTime = $("#beginTime").val();
        var endTime = $("#endTime").val();
        var d1 = new Date(beginTime.replace(/\-/g, "\/"));
        var d2 = new Date(endTime.replace(/\-/g, "\/"));
        console.log(d1);
        if (beginTime != "" && endTime != "" && d1 >= d2) {
            layer.msg("开始时间不能大于结束时间！");
            return false;
        }
        var mode = $('input[name="qiang"]:checked').val();
        if (mode == 'p') {
            // 是否选择工程师
            var checkids = [];
            var ids = "";
            $("input[name='manageid']:checked").each(function (i) {
                checkids[i] = $(this).val();
            });
            if (checkids.length == 0) {
                layer.msg("请选择工程师！");
                return false;
            }
            ids = checkids.join(",");
            $("#manageids").val(ids);
        }


        $("#form").submit();
    }
</script>

<?php


if (isset($action) and $action == 'add') {
    if (empty($content)) {
        echo "<script>layer.msg('请输入必要的信息');</script>";
        exit();
    }

    // 工单信息入库
    $apply_type = htmlspecialchars($apply_type);
    $apply_device = htmlspecialchars($apply_device);
    $jindu = "3";
    $latitude = "33.006170";
    $longitude = "114.015880";
    $accuracy = "14";
    $post_time = time();
    $post_time2 = date("Y-m-d H:i:s", time());
    $beginTime = strtotime($beginTime);
    $endTime = strtotime($endTime);


//    $fee = "";
//    //调取任务奖励
//    if ($repairid > 0) {
//        $fee_arr = $dosql->GetOne("SELECT * FROM `#@__cascadedata` WHERE   datagroup='renwu' AND  datavalue='$repairid'  ORDER BY id desc");
//        if (is_array($fee_arr) && isset($fee_arr['id'])) {
//            $fee = $fee_arr['fee'];
//        }
//    }
    //调取 用户数据
    if ($crmid > 0) {
        $crm_arr = $dosql->GetOne("SELECT * FROM `#@__crm` WHERE   checkinfo='true' AND  id='$crmid' ");
        if (is_array($crm_arr) && isset($crm_arr['id'])) {
            $school = $crm_arr['school'];
            $address = $crm_arr['address'];
            $mobile = $crm_arr['mobile'];
            $truename = $crm_arr['truename'];
            if ($crm_arr['gps'] != "") {
                $gps_arr = explode(',', $crm_arr['gps']);

                if (is_array($gps_arr) && isset($gps_arr[1])) {
                    $latitude = $gps_arr[0];
                    $longitude = $gps_arr[1];
                }

            }
            $crm_uid = "";  //用户的 uid
            $crm_openid_str = "";
            if ($crm_arr['uid'] > 0) {
                $crm_uid = $crm_arr['uid'];
                $crm_openid = $dosql->GetOne("select openid  from `#@__user`  where id='$crm_uid'");
                $crm_openid_str = $crm_openid['openid'];  //用户的 openid
            }


        }
    } else {
        echo "<script>layer.msg('没有选择客户，请选择');</script>";
        exit();
    }


    $remark_info = GetAuthor() . " 直接创建任务";


    if ($qiang == 'p') {
        $op_op_name = GetAuthor() . ' 派单';
        //新建工单
        $sql2 = "insert into `#@__order`(openid,uid,school,truename,mobile,address,apply_type,apply_device,repairid,num,content,manageid,begintime,endtime,post_time,jindu,latitude,longitude,accuracy,delstate,poster,remark,remark_time,fee,crmid,is_accept,accept_time,qiang) values   ('$crm_openid_str','$crm_uid','$school','$truename','$mobile','$address','$apply_type','$apply_device','$repairid','$num','$content','$manageids','$beginTime','$endTime','$post_time','$jindu','$latitude','$longitude','$accuracy','','$poster','$remark_info','$post_time','$fee','$crmid','1','$post_time','$qiang')";
        $dosql->ExecNoneQuery($sql2);
        $orderid = $dosql->GetLastID();
    }
    if ($qiang == 'q') {
        $op_op_name = GetAuthor() . ' 发布抢单';
        //新建工单
        $sql2 = "insert into `#@__order`(openid,uid,school,truename,mobile,address,apply_type,apply_device,repairid,num,content,manageid,begintime,endtime,post_time,jindu,latitude,longitude,accuracy,delstate,poster,remark,remark_time,fee,crmid,is_accept,accept_time,qiang) values   ('$crm_openid_str','$crm_uid','$school','$truename','$mobile','$address','$apply_type','$apply_device','$repairid','$num','$content','$manageids','$beginTime','$endTime','$post_time','2','$latitude','$longitude','$accuracy','','$poster','$remark_info','$post_time','$fee','$crmid','1','$post_time','$qiang')";
        $dosql->ExecNoneQuery($sql2);
        $orderid = $dosql->GetLastID();
    }

    $dosql->ExecNoneQuery("insert into `#@__order_log`(orderid,op,op_time,jindu,manageid) values ('$orderid','$op_op_name','$post_time','2','$op_uid')");


    // 判断工单的 模式  q 抢单 p 派单

    if ($qiang == 'p') {
        $ids_arr = explode(",", $manageids);
        //执行人
        $zhixingren = "";
        foreach ($ids_arr as $key => $val) {
            $zhixingren .= getManage($val) . "    ";
        }

        //处理工单
        foreach ($ids_arr as $key => $val) {
            //获取工程师 openid
            $m = $dosql->GetOne("select openid  from `#@__user`  where id='$val'");
            $openid_str = $m['openid'];
            //插入更新的状态

            $dosql->ExecNoneQuery("insert into `#@__order_log`(orderid,op,op_time,jindu,manageid) values ('$orderid','系统已经派单','$post_time','3','$val')");
            $orderidname = date('Ymd', time()) . "-" . $orderid;
            //封装为json格式的数据
            $repairname = getRepairMode($repairid);
            if($num>0){
                $repairname=$repairname." 数量 ".$num."  奖励  ".$fee;
            }
            $json2 = '{
			  "touser": "' . $openid_str . '" ,  
			  "template_id": "'.$cfg_order_status.'",    
			  "url":"'.$cfg_weburl.'wx/morderDetail.php?orderid=' . $orderid . '",  
			  "data": {
				  "first": {
					  "value": "您好，系统下发任务成功。请处理", 
					  "color": "#f71b03"
				  }, 
				  "keyword1": {
					  "value": "' . $orderidname . '", 
					  "color": "#173177"
				  }, 
				  "keyword2": {
					  "value": "' . $post_time2 . '", 
					  "color": "#173177"
				  },
				  "keyword3": {
					  "value": "' . $zhixingren . '", 
					  "color": "#0e48cb"
				  },
				  "keyword4": {
					  "value": " ' . $repairname . '", 
					  "color": "#173177"
				  },
				  "keyword5": {
					  "value": "' . $op_op_name . '", 
					  "color": "#173177"
				  },
				  "remark": {
					  "value": "请点击处理，如有特殊情况，请转单给其他工程师。服务热线：'.$cfg_hotline.'", 
					  "color": "#f71b03"
				  } 
			  }
			}';
            sendWxMsg($json2);
        }

    }

    // 抢单模式

    if ($qiang == 'q') {
        //获取抢单的工程师
        $qiang_user=array();
        $dosql->Execute("SELECT `openid` FROM  `#@__user`  WHERE level='3' and qiang='1'  ORDER BY id asc");
        while ($row_qaing = $dosql->GetArray()) {
           $qiang_user[]=$row_qaing['openid'];
        }

        //处理工单
        foreach ($qiang_user as $key => $val) {
            //获取工程师 openid
            $openid_str = $val;

            $orderidname = date('Ymd', time()) . "-" . $orderid;
            //封装为json格式的数据
            $repairname = getRepairMode($repairid);
            if($num>0){
                $repairname=$repairname." 数量 ".$num."  奖励  ".$fee;
            }
            $json2 = '{
			  "touser": "' . $openid_str . '" ,  
			  "template_id": "'.$cfg_qiangsendtpl.'",    
			  "url":"'.$cfg_weburl.'wx/morderDetail.php?orderid=' . $orderid . '",  
			  "data": {
				  "first": {
					  "value": "您好，系统下发抢单任务成功。请处理", 
					  "color": "#f71b03"
				  }, 
				  "keyword1": {
					  "value": "' . $orderidname . '", 
					  "color": "#173177"
				  }, 
				  "keyword2": {
					  "value": "' . $repairname . '", 
					  "color": "#173177"
				  },
				  "keyword3": {
					  "value": "'.$post_time2.'", 
					  "color": "#0e48cb"
				  },
				  "keyword4": {
					  "value": " ' . $op_op_name . '", 
					  "color": "#173177"
				  },
				  "remark": {
					  "value": "请点击抢单，手慢无哦。'.$cfg_qiangout.'分钟无人接单，系统按照工作忙闲程度分配工单，全部空闲时随机指派；服务热线：'.$cfg_hotline.'", 
					  "color": "#f71b03"
				  }
			  }
			}';
            sendWxMsg($json2);
        }

    }


    echo '<script type="text/javascript">
					layer.alert("任务添加成功",function(){
						window.parent.location.reload();
						layer.close();
					})

	</script>';
    exit();

}

?>

</body>
</html>